package com.example.backend.service.impl;

import com.example.backend.entity.StorageIn;
import com.example.backend.entity.StockRecord;
import com.example.backend.mapper.StorageInMapper;
import com.example.backend.service.StorageInService;
import com.example.backend.service.StockRecordService;
import com.example.backend.service.WarehouseAllocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.backend.mapper.WarehouseMapper;
import com.example.backend.entity.Warehouse;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
@Service
public class StorageInServiceImpl implements StorageInService {
    @Autowired
    private StorageInMapper storageInMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;
    
    @Autowired
    private WarehouseAllocationService warehouseAllocationService;
    
    @Autowired
    private StockRecordService stockRecordService;

    @Override
    public int addStorageIn(StorageIn storageIn) {
        try {
            
            // 使用仓库分配服务进行空闲仓库分配，支持分到多个仓库
            List<WarehouseAllocationService.AllocationResult> allocations = 
                warehouseAllocationService.allocateWarehousesForStorageIn(
                    storageIn.getCompanyId(), 
                    storageIn.getPortId(),
                    storageIn.getInWeight().doubleValue()
                );
            // 先插入入库记录（包含companyId和portId，但不包含warehouseId）
            storageInMapper.insert(storageIn);
            // 为每个分配的仓库创建库存记录
            for (WarehouseAllocationService.AllocationResult allocation : allocations) {
                StockRecord stockRecord = new StockRecord();
                stockRecord.setInId(storageIn.getId());
                stockRecord.setCompanyId(storageIn.getCompanyId());
                stockRecord.setPortId(allocation.getPortId());
                stockRecord.setWarehouseId(allocation.getWarehouseId());
                stockRecord.setOriginalWeight(java.math.BigDecimal.valueOf(allocation.getAllocatedWeight()));
                stockRecord.setRemainingWeight(java.math.BigDecimal.valueOf(allocation.getAllocatedWeight()));
                stockRecord.setInDate(storageIn.getInDate());
                stockRecord.setOrderNumber(storageIn.getOrderNumber());
                stockRecord.setStatus(1); // 有库存
                
                // 插入库存记录
                stockRecordService.addStockRecord(stockRecord);
                
                // 更新仓库容量
                warehouseAllocationService.updateWarehouseCapacity(
                    allocation.getWarehouseId(), 
                    allocation.getAllocatedWeight()
                );
            }
            
            return 1;
            
        } catch (RuntimeException e) {
            // 如果是容量不足的异常，直接抛出
            if (e.getMessage().contains("该港口装不下这么多货物") || 
                e.getMessage().contains("该港口下没有可用仓库")) {
                throw e;
            }
            
            // 其他异常，包装成更友好的信息
            throw new RuntimeException("入库失败：" + e.getMessage(), e);
        }
    }

    @Override
    public StorageIn getStorageInById(Long id) {
        return storageInMapper.selectById(id);
    }

    @Override
    public List<StorageIn> getAllStorageIn() {
        return storageInMapper.selectAll();
    }

    @Override
    public int updateStorageIn(StorageIn storageIn) {
        return storageInMapper.update(storageIn);
    }

    @Override
    public int deleteStorageIn(Long id) {
        return storageInMapper.deleteById(id);
    }

//    @Override
//    public List<StorageIn> getByOrderNumber(String orderNumber) {
//        return storageInMapper.selectByOrderNumber(orderNumber);
//    }

    @Override
    public List<StorageIn> getStorageInByPortId(Long portId) {
        return storageInMapper.selectByPortId(portId);
    }
    
    @Override
    public List<StorageIn> getUnOutByCompanyAndPortOrderByDate(Long companyId, Long portId) {
        return storageInMapper.selectUnOutByCompanyAndPortOrderByDate(companyId, portId);
    }
    
    @Override
    public List<StorageIn> getByCompanyAndWarehouse(Long companyId, Long warehouseId) {
        return storageInMapper.selectByCompanyAndWarehouse(companyId, warehouseId);
    }

    @Override
    @Transactional
    public int batchAddStorageIn(List<StorageIn> storageInList) {
        int successCount = 0;
        log.info("开始批量插入，共{}条数据", storageInList.size());
        
        for (int i = 0; i < storageInList.size(); i++) {
            StorageIn storageIn = storageInList.get(i);
            try {
                log.info("正在插入第{}条数据: {}", i + 1, storageIn);
                addStorageIn(storageIn);
                successCount++;
                log.info("第{}条数据插入成功", i + 1);
            } catch (Exception e) {
                log.error("第{}条数据插入失败: {}", i + 1, e.getMessage(), e);
                // 遇到异常立即停止，事务会回滚
                throw new RuntimeException("批量插入失败，第" + (i + 1) + "条数据出错: " + e.getMessage(), e);
            }
        }
        
        log.info("批量插入完成，成功插入{}条数据", successCount);
        return successCount;
    }

    @Override
    public int deleteAll() {
        return storageInMapper.deleteAll();
    }
} 